/*
 * These files are distributed under the terms of the GNU GPLv2, the GNU General
 * Public version 2. See LICENSE.txt
 */
package fileCommodore.plugin.file_info;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;

import fileCommodore.model.*;
import fileCommodore.view.*;

/**
 * @author nado18@gmail.com, on Jul 27, 2007
 */
public class GroupInfoPane extends JPanel
{
	private JCheckBox cbRecursive = new JCheckBox( "Recursive Size" );
	private JPanel labelPane = new JPanel();
	private LinkedHashMap<String, String> props =
			new LinkedHashMap<String, String>();
	
	private Vector<FileRowItem> items = new Vector<FileRowItem>();
	
	private JLabel[][] labels;
	
	public GroupInfoPane(String title)
	{
		props.put( "Count", "" );
		props.put( "Size", "" );
		
		setLayout( new BorderLayout() );
		add( cbRecursive, BorderLayout.NORTH );
		add( labelPane, BorderLayout.CENTER );
		
		labels = new JLabel[props.size()][2];
		labelPane.setLayout( new GridLayout( props.size(), 2 ) );
		int y = 0;
		for (String key : props.keySet())
		{
			JLabel keyLabel = new JLabel( String.format( "%s:", key ) );
			keyLabel.setHorizontalAlignment( JLabel.RIGHT );
			JLabel valueLabel = new JLabel();
			
			labels[y][0] = keyLabel;
			labels[y][1] = valueLabel;
			
			labelPane.add( keyLabel );
			labelPane.add( valueLabel );
			
			y++;
		}
		
		setBorder( BorderFactory.createTitledBorder( title ) );
		
		cbRecursive.addItemListener( new ItemListener()
		{
			public void itemStateChanged( ItemEvent e )
			{
				update();
			}
		} );
	}
	
	private Thread sizeThread;
	
	private void update()
	{
		if (null != sizeThread)
		{
			sizeThread.interrupt();
		}
		
		boolean isRecursive = cbRecursive.isSelected();
		String size =
				isRecursive
						? "Calculating..."
						: MyLabelProvider.friendlySize( getFileSize( items ) );
		
		props.put( "Count", Integer.toString( items.size() ) );
		props.put( "Size", size );
		
		int y = 0;
		for (String value : props.values())
		{
			labels[y++][1].setText( value );
		}
		
		if (isRecursive)
		{
			RecursiveSizeCounter rsc =
					new RecursiveSizeCounter( items, labels[1][1] );
			sizeThread = new Thread( rsc );
			sizeThread.start();
		}
	}
	
	public void setItems( Vector<FileRowItem> items )
	{
		this.items = items;
		
		update();
	}
	
	public static long getFileSize( Collection<FileRowItem> items )
	{
		long sum = 0;
		
		for (FileRowItem item : items)
		{
			if (null != item)
			{
				if (item.isFile())
				{
					sum += item.getRecursiveSize();
				}
			}
		}
		
		return sum;
	}
	
	public static long getRecursiveSize( Collection<FileRowItem> items )
	{
		long sum = 0;
		
		for (FileRowItem item : items)
		{
			if (null != item)
			{
				sum += item.getRecursiveSize();
			}
		}
		
		return sum;
	}
	
}
